package com.xiyueyezi.xiyueyezi.utils;
import android.content.Intent;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.style.ClickableSpan;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;

import java.util.Map;

/**
 * @author Xiyueyezi
 * @Description
 * @since 2024-2024/8/5 11:30
 */
public class LinkifyUtils {

    /**
     * 创建可点击的字符SpannableString
     * @param value 待处理的字符串
     * @param links 需显示为链接的词汇（如用户协议、隐私协议等）
     * @return SpannableString
     */
    public static CharSequence createClickableSpans(String value, Map<String, Intent> links) {
        SpannableString spannableString = new SpannableString(value);

        for (Map.Entry<String, Intent> entry : links.entrySet()) {
            String linkText = entry.getKey();
            Intent intent = entry.getValue();

            int start = value.indexOf(linkText);
            while (start != -1) {
                spannableString.setSpan(new ClickableSpan() {
                    @Override
                    public void onClick(@NonNull View widget) {
                        widget.getContext().startActivity(intent);
                    }

                    @Override
                    public void updateDrawState(@NonNull TextPaint ds) {
                        super.updateDrawState(ds);
                        ds.setUnderlineText(false); // 移除下划线
                    }
                }, start, start + linkText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                // 查找下一个匹配的词汇
                start = value.indexOf(linkText, start + linkText.length());
            }
        }

        return spannableString;
    }
}
